package com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.dao.UserDao;
import com.pojo.UserPojo;
import com.service.UserService;

@Controller
@RequestMapping(value = "/user")

public class UserController{
	@Autowired
	public UserService userService;

    @RequestMapping(value="/addUser1",method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String addUser1(HttpServletResponse response,HttpServletRequest request){
    	System.out.println("addUser1");
    	String name = (String)request.getParameter("name");
    	String age = request.getParameter("age");
    	//TODO 写入数据库
    	String result = "{'resultCode':'0000','name':'"+name+"'}";
    	return result;
    }
    //与addUser1效果一样
    @RequestMapping(value="/addUser2",method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String addUser2(UserPojo userPojo,HttpServletResponse response,HttpServletRequest request){
    	System.out.println("addUser2");
    	String name = userPojo.getName();
    	//TODO 写入数据库
    	String result = "{'resultCode':'0000','name':'"+name+"'}";
    	return result;
    }
    
    @RequestMapping(value="/addUser3",method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void addUser3(HttpServletResponse response,HttpServletRequest request){
    	System.out.println("addUser3");
    	String name = request.getParameter("name");
        Map<String,Object> jsonMap = new HashMap<String,Object>();
        jsonMap.put("name",name);
        jsonMap.put("resultCode", "0000");
    	response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
		try {
			out = response.getWriter();
	        out.print(JSON.toJSONString(jsonMap));
	        out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(out != null)
				out.close();
		}
    }
    //与addUser3类似
    @RequestMapping(value="/addUser4",method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void addUser4(UserPojo userPojo,HttpServletResponse response,HttpServletRequest request){
    	System.out.println("addUser4");
    	String name = userPojo.getName();
    	Integer age = userPojo.getAge();
        Map<String,Object> jsonMap = new HashMap<String,Object>();
        jsonMap.put("name",name);
        jsonMap.put("resultCode", "0000");
    	response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
		try {
			out = response.getWriter();
	        out.print(JSON.toJSONString(jsonMap));
	        out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(out != null)
				out.close();
		}
    }
    
    //测试调用两个具有事务的方法的回滚情况
    //@Transactional //加在Controller方法的事务注解不起作用，应该怎么配置？不过最好还是通过在service层加事务
    @RequestMapping(value="/addUser5",method=RequestMethod.POST)
    public void addUser5(UserPojo userPojo,HttpServletResponse response,HttpServletRequest request){
    	String name = userPojo.getName();
    	Integer age = userPojo.getAge();
        Map<String,Object> jsonMap = new HashMap<String,Object>();
    	try {
    		//下面两个事务是独立的两个事务，不会互相影响
			userService.addUser(name,age);//成功执行，直接就提交事务了
			userService.addUser(name,-1);//抛出异常，事务回滚，仅回滚自己
	        jsonMap.put("result","增加用户("+name+"）成功");
	        jsonMap.put("resultCode", "0000");
		} catch (Exception e1) {
	        jsonMap.put("result","增加用户("+name+"）异常");
	        jsonMap.put("resultCode", "9999");
		}
    	response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
		try {
			out = response.getWriter();
	        out.print(JSON.toJSONString(jsonMap));
	        out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(out != null)
				out.close();
		}
    }
    
	// 测试调用手动事务
	@RequestMapping(value = "/addUser6", method = RequestMethod.POST)
	public void addUser6(UserPojo userPojo, HttpServletResponse response, HttpServletRequest request) {

		String name = userPojo.getName();
		Integer age = userPojo.getAge();
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		int result = userService.addUserWithManualTransactional(name, age);
		if (result > 0) {
			jsonMap.put("result", "增加用户(" + name + "）成功");
			jsonMap.put("resultCode", "0000");
		} else {
			jsonMap.put("result", "增加用户(" + name + "）失败");
			jsonMap.put("resultCode", "9999");
		}
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(JSON.toJSONString(jsonMap));
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null)
				out.close();
		}
	}

    
    
    
}
